/**
 * Created by liupan on 2017-3-8.
 * 设备管理界面js
 * 对应JSP为device.jsp
 */
define(["require", "jquery", "public/app", "mustache"], function (require, $, app, mustache) {

    function Device($container) {
        this._$container = $container;
        this._init();
    }

    Device.prototype._initUrlPath = function () {
        this.urlPaths = {
            listHostGroup: app.urlBuild("/dirms/monitor/group/list"),
            queryHostByGroupid: app.urlBuild("/dirms/monitor/host/get/"),
            queryAppByHostid: app.urlBuild("/dirms/monitor/application/get/"),
            queryItemByAppid: app.urlBuild("/dirms/monitor/item/getByAppId/"),
            queryGraphByItemid: app.urlBuild("/dirms/monitor/graph/get/"),
            queryHistoryByItemid: app.urlBuild("/dirms/monitor/history/get/"),
            queryTrendByItemid: app.urlBuild("/dirms/monitor/trend/get/"),
            addDeviceTemplateJsp: app.urlBuild("/pages/app/device/addDeviceTemplate.jsp"),
            queryDeviceExtend: app.urlBuild("/dirms/monitor/hostgroupType/queryHostgroup"),
            addDeviceInfoJsp: app.urlBuild("/pages/app/device/addDeviceInfo.jsp"),
        }
    };

    Device.prototype._init = function () {
        this._initUrlPath();
        this._initComponents();
        // var self = this;
        // var dataReady = app.getDataReady();
        //
        // dataReady.pushDataSource({//逐个放入所有数据源
        //     url: this.urlPaths.listHostGroup,
        //     key: 'HostGroupData'
        // });

        // dataReady.once(function (readyData) {
        //     self._initComponents(readyData);
        // });
    };

    Device.prototype._initComponents = function (readyData) {
        //初始化控件
        this._initDeviceGrid(readyData);//初始化用户表格
        this._initEventBinding(this);//初始化事件绑定
        this._initSearch();//初始化搜索
    };

    var DeviceGrid;
    Device.prototype._initSearch = function () {
        var self = this;
        //主表格搜索框
        $('#searchMenu').searchbox({
            //搜索功能未完成，应按照用户、角色、组织机构三类来进行搜索
            searcher: function (value, name) {
                if(name == 'name' && value != ""){
                    $.ajax({
                        type: "POST",
                        url: self.urlPaths.QueryTemplateByName + value,
                        success:function(data){
                            if(data == ""||data == null){alert(value+" 设备不存在");}
                            else{
                                $('#deviceGrid').datagrid('loadData',data);
                                $('#searchMenu').searchbox('clear');
                            }
                        },
                        error:function(){alert("查询错误");}
                    });
                }
                // else{
                //     $('#_UserGrid').datagrid('reload');
                // }
            },
            menu: '#search',
            prompt: '请输入关键字'
        });
    };
    Device.prototype._getResTypeName = function (resTypeId) {
        var resTypeName = resTypeId;
        switch (resTypeId) {
            case 0:
                resTypeName = "容器";
                break;
            case 1:
                resTypeName = "组";
                break;
            case 2:
                resTypeName = "主机";
                break;
            case 3:
                resTypeName = "应用集";
                break;
            case 4:
                resTypeName = "监控项";
                break;
        }
        return resTypeName;
    };
    Device.prototype._getButtonActionByResType = function (resTypeId) {
        var addDevice = '<a href="#" class="easyui-linkbutton add_device" plain="true" iconCls="icon-add">添加设备</a>  ';
        var addGroup = '<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add">添加组</a>  ';
        var addMonitorNode = '<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add">添加监测点</a>  ';
        var addApplication = '<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add">添加应用集</a>  ';
        var editItem = '<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add">编辑</a>  ';
        var delItem = '<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add">删除</a>  ';
        var test = '<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add">测试</a>  ';
        var result = "";
        switch (resTypeId) {
            case 0:
                result = addDevice + addGroup + editItem;
                break;
            case 1:
                result = addDevice + addGroup + editItem + delItem;
                break;
            case 2:
                result = addApplication + editItem + delItem;
                break;
            case 3:
                result = addMonitorNode + editItem + test;
                break;
            case 4:
                result = editItem + test;
                break;
        }
        return result;
    };
    Device.prototype._getUrlByResType = function (row) {
        var url = null;
        switch (row.type) {
            case 0:
                break;
            case 1:
                url = this.urlPaths.queryHostByGroupid + row.id;
                break;
            case 2:
                url = this.urlPaths.queryAppByHostid + row.id;
                break;
            case 3:
                url = this.urlPaths.queryItemByAppid + row.id;
                break;
            case 4:
                break;
        }
        return url;
    };
    //初始化表格
    Device.prototype._initDeviceGrid = function (readyData) {
        var self = this;
        DeviceGrid=$('#deviceGrid').treegrid({
            // rownumbers: true,
            // pagination: true,
            // fitColumns: true,
            // data: readyData.HostGroupData.data,
            animate: true,
            singleSelect: true,
            url: self.urlPaths.listHostGroup,
            method: 'post',
            title: '',
            width: 'auto',
            height: '100%',
            region: 'south',
            idField: 'id',
            treeField: 'name',
            striped: true, // 蒙版效果
            // parentField: 'groupid',
            //对应model层字段
            columns: [[
                {field:'name',title:"名称",width: '350'},
                {field: 'type', title: '类型', width: '200', formatter: function (value, row, index) {
                    if (row) {
                        return self._getResTypeName(row.type);
                    }
                }},
                {field: 'updatetime', title: '最新数据时间', width: '100'},
                {field: 'operation', title: '操作', width: '200', formatter: function (value, row, index) {
                    return self._getButtonActionByResType(row.type);
                }},
            ]],
            toolbar: this._$container.find("#Toolbar"),
            onBeforeExpand: function(row){
                if (row) {
                    var url = self._getUrlByResType(row);
                    $('#deviceGrid').treegrid("options").url = url;
                }
                return true;
            },
            onClickRow: function (row) {
                if (row) {
                    if (row.type == 4) {
                        $.ajax({
                            type:"POST",
                            url:self.urlPaths.queryTrendByItemid+row.id,
                            success:function(data){
                                console.log(data);

                                $("#iteminfo_panel").css("display","inline-block");
                                $("#iteminfo_panel").removeClass("a-fadeout").addClass("a-fadein").show("slow");
                            },
                            error:function(){alert("查询错误");}
                        });
                    }
                }
            },
        });
    };

    /**
     * 结束编辑模板
     */
    Device.prototype._endEditTemplate = function () {
        var self = this;
        if (self.editIndex == undefined){return true}
        if ($('#deviceGrid').datagrid('validateRow', self.editIndex)){
            var ed = $('#deviceGrid').datagrid('getEditor', {index:self.editIndex,field:'icon'});
            var name = $(ed.target).combobox('getText');
            var value = $(ed.target).combobox('getValue');
            $('#deviceGrid').datagrid('getRows')[self.editIndex]['icon'] = name;
            $('#deviceGrid').datagrid('getRows')[self.editIndex]['iconname'] = name;
            $('#deviceGrid').datagrid('getRows')[self.editIndex]['iconid'] = value;
            $('#deviceGrid').datagrid('endEdit', self.editIndex);
            self.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };


        /**
         * 事件绑定
         */
        Device.prototype._initEventBinding = function (self) {
            //【todo 在此编写绑定事件的方法。如按钮需要绑定的click事件。建议按如下格式绑定，并将this作为参数传入】
            //egg
            //用户管理首页五个按钮
            // this._$container.find('#adduser_btn').on('click', {self: this}, this._actions.adduserClick);
            this._$container.find('#edittemplate_btn').on('click', {self: this}, this._actions.editTemplateClick);
            // this._$container.find('#deleteuser_btn').on('click', {self: this}, this._actions.deleteuserClick);
            this._$container.find('#accepttemplate_btn').on('click', {self: this}, this._actions.acceptTemplateClick);
            this._$container.find('#rejecttemplate_btn').on('click', {self: this}, this._actions.rejectTemplateClick);
            this._$container.find('#iteminfo_close_btn').on('click', {self: this}, this._actions.iteminfoCloseClick);
            this._$container.find('#devicetype_close_btn').on('click', {self: this}, this._actions.iteminfoCloseClick);
            this._$container.on("click", ".add_device", {self: this}, this._actions.addDeviceClick);
            this._$container.on("click", "#deviceTemplate", {self: this}, showDeviceInfoDialog);
        };


        /**
         * 在此定义此js用到的事件处理方法。如处理按钮click事件的方法
         * @type {{btcClick: Function}}
         */
        Device.prototype._actions = {
            iteminfoCloseClick: function (evt) {
                // $(this).parent().hide("slow");
                $(this).parent().removeClass("a-fadein").addClass("a-fadeout").show("slow");
                $(this).parent().css("display","none");

            },
            //模板编辑按钮事件
            editTemplateClick: function(evt){
                //获取这一行内容
                var row = $("#deviceGrid").datagrid('getSelections');
                if (row == undefined||row.length==0 ) {
                    $.messager.alert('提示',"请选择编辑对象",'info');
                    return;
                }else if(row.length>1){
                    $.messager.alert('提示',"只能选择单条记录",'info');
                    return;
                }
                showTemplateDialog(evt,row);
            },
            acceptTemplateClick: function (evt) {
                if (evt.data.self._endEditTemplate()){
                    var changes = $('#deviceGrid').datagrid('getChanges');
                    var dataJson = [];
                    $.each(changes, function (index) {
                        var dataMap = {};
                        dataMap.iconsId = this.iconid;
                        dataMap.templateId = this.templateid;
                        dataJson.push(dataMap);
                    });

                    $.ajax({
                        url: evt.data.self.urlPaths.SaveTemplateIcons,
                        type: "POST",
                        cache: false,
                        contentType: "application/json",
                        dataType: "json",
                        data : JSON.stringify(dataJson),
                        success: function(data){
                            $('#deviceGrid').datagrid('acceptChanges');
                            $.messager.alert('提示：','修改成功');
                        },
                        error: function () {
                            $('#deviceGrid').datagrid('rejectChanges');
                            evt.data.self.editIndex = undefined;
                            $.messager.alert('提示','修改失败！','info');
                        }
                    });
                }
            },
            rejectTemplateClick: function (evt) {
                $('#deviceGrid').datagrid('rejectChanges');
                evt.data.self.editIndex = undefined;
            },
            addDeviceClick: function (evt) {

                // for test data
                // var hostgroups = [
                //     {groupName: "数据库",templates:[{templateName:"Oracle",iconUrl:"url"},{templateName:"Mysql",iconUrl:"url"}]},
                //     {groupName: "Linux",templates:[{templateName:"Centos",iconUrl:"url"}]},
                //     {groupName: "windows",templates:[{templateName:"windows server 2003",iconUrl:"url"}]},
                // ];
                // var hostgroupsType = [
                //     {id: "1", name:"服务器", hostgroups: hostgroups},
                //     {id: "2", name:"应用与业务", hostgroups: hostgroups},
                //     {id: "3", name:"虚拟机", hostgroups: hostgroups},
                //     {id: "4", name:"其他", hostgroups: hostgroups},
                // ];

                $.ajax({
                    url: evt.data.self.urlPaths.queryDeviceExtend,
                    type: "POST",
                    cache: false,
                    contentType: "application/json",
                    async : false,
                    beforeSend:function(XMLHttpRequest){
                        $.messager.progress({
                            title : '提示信息！',
                            text : '数据处理中，请稍后....'
                        });
                    },
                    success: function(data){
                        $.messager.progress('close');
                        if(typeof(data) != "undefined" && data != null && data != ''){
                            $.each(data, function (index) {
                                var typeSelf  = this;
                                $.get(evt.data.self.urlPaths.addDeviceTemplateJsp, function (deviceData, status, relt) {
                                    if ("success" == status) {
                                        var rendered = mustache.render(deviceData, {
                                            hostgroups: typeSelf.hostgroups
                                        });
                                        addTab(typeSelf.name, null, rendered);
                                    } else {
                                        $.messagerShow("查询设备类型失败！");
                                    }
                                });
                            });
                        }
                    },
                    error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                        $.messager.progress('close');
                        $.messager.alert('提示','数据获取失败！','info')
                    }
                });

                // $.each(hostgroupsType, function (index) {
                //     var typeSelf  = this;
                //     $.get(evt.data.self.urlPaths.addDeviceTemplateJsp, function (data, status, relt) {
                //         if ("success" == status) {
                //             var rendered = mustache.render(data, {
                //                 hostgroups: typeSelf.hostgroups
                //             });
                //             addTab(typeSelf.name, null, rendered);
                //         } else {
                //             $.messagerShow("查询设备类型失败！");
                //         }
                //     });
                // });

                // $('#device_type_tabs').tabs("select",0);
                $("#add_device_panel").css("display","inline-block");
                $("#add_device_panel").removeClass("a-fadeout").addClass("a-fadein").show("slow");
            },

            addDeviceInfoClick: function (evt) {

            },
        };

        var addTab = function(title, url, content){
            if ($('#device_type_tabs').tabs('exists', title)){
                $('#device_type_tabs').tabs('select', title);
            } else {
                $('#device_type_tabs').tabs('add',{
                    title:title,
                    // href: url,
                    content: content,
                });
            }
        }

        /**
         *
         * @param evt 点击时间
         * @param row  行记录数据
         */
        var showTemplateDialog = function(evt,row){
            var inputUrl = evt.data.self.urlPaths.TemplateEdit;
            var iconDataUrl = evt.data.self.urlPaths.IconsData;
            if (typeof(row) == 'undefined' || row.length != 1) {
                return;
            }
            var title="编辑模板";
            //对话框
            var templateEditdialog = $('<div id="template-edit"/>').dialog({
                title : title,
                top:100,
                width : 500,
                /*          height : 360,*/
                modal : true, //模式窗口：窗口背景不可操作
                resizable : false, //可拖动边框大小
                plain : true,
                href : inputUrl,
                buttons : [ {
                    text : '确定',
                    iconCls : 'icon-ok',
                    plain : true,
                    handler : function() {
                        var templateData = $("#templateEdit").serializeJsonStr();

                        var isValid = $('#templateEdit').form('validate');
                        if(!isValid){
                            return ;
                        }
                        $.ajax({
                            url:evt.data.self.urlPaths.UpdateTemplateData,
                            type:"POST",
                            cache:false,
                            contentType: "application/json",
                            async : false,
                            dataType: "json",
                            data : templateData,
                            beforeSend:function(XMLHttpRequest){
                                $.messager.progress({
                                    title : '提示信息！',
                                    text : '数据处理中，请稍后....'
                                });
                            },
                            success: function(data){
                                $.messager.progress('close');
                                if(typeof(data) != "undefined" && data !=null && data!=''){
                                    $.messager.alert('提示','保存成功！','info');
                                    $("#deviceGrid").datagrid('reload');//重新加载列表数据
                                    $("#template-edit").dialog('destroy');//销毁对话框
                                }
                            },
                            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                                $.messager.progress('close');
                                $.messager.alert('提示','数据保存失败！','info')
                            }
                        });
                    }
                }, {
                    text : '取消',
                    iconCls : 'icon-cancel',
                    plain : true,
                    handler : function() {
                        $("#template-edit").dialog('destroy');//销毁对话框
                    }
                } ],
                onClose : function() {
                    $(this).dialog('destroy');
                },
                onLoad : function() {
                    /*user_input_form_init(evt);*/
                    //编辑
                    if(row != undefined && row.length==1){
                        // var id=row[0].id;
                        $("#icon").combobox({
                            url: iconDataUrl,
                            valueField: "value",
                            textField: "name",
                            method: 'get',
                            editable: true,
                            required: true,
                        });
                        $("#templateEdit").form("load",row[0]);
                        // $('#id').val(id);
                    }
                }
            }).dialog('open');
        };

    /**
     *
     * @param evt 点击时间
     * @param row  行记录数据
     */
    var showDeviceInfoDialog = function(evt){
        var inputUrl = evt.data.self.urlPaths.addDeviceInfoJsp;
        //对话框
        var deviceAdddialog = $('<div id="device_info_add"/>').dialog({
            title : "添加设备",
            top:100,
            width : 500,
            /*          height : 360,*/
            modal : true, //模式窗口：窗口背景不可操作
            resizable : false, //可拖动边框大小
            plain : true,
            href : inputUrl,
            buttons : [ {
                text : '确定',
                iconCls : 'icon-ok',
                plain : true,
                handler : function() {
                    var templateData = $("#device_info_form").serializeJsonStr();

                    var isValid = $('#device_info_form').form('validate');
                    if(!isValid){
                        return ;
                    }
                    $.ajax({
                        url:evt.data.self.urlPaths.UpdateTemplateData,
                        type:"POST",
                        cache:false,
                        contentType: "application/json",
                        async : false,
                        dataType: "json",
                        data : templateData,
                        beforeSend:function(XMLHttpRequest){
                            $.messager.progress({
                                title : '提示信息！',
                                text : '数据处理中，请稍后....'
                            });
                        },
                        success: function(data){
                            $.messager.progress('close');
                            if(typeof(data) != "undefined" && data !=null && data!=''){
                                $.messager.alert('提示','保存成功！','info');
                                $("#deviceGrid").datagrid('reload');//重新加载列表数据
                                $("#device_info_add").dialog('destroy');//销毁对话框
                            }
                        },
                        error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                            $.messager.progress('close');
                            $.messager.alert('提示','数据保存失败！','info')
                        }
                    });
                }
            }, {
                text : '取消',
                iconCls : 'icon-cancel',
                plain : true,
                handler : function() {
                    $("#device_info_add").dialog('destroy');//销毁对话框
                }
            } ],
            onClose : function() {
                $(this).dialog('destroy');
            },
            // onLoad : function() {
            //     /*user_input_form_init(evt);*/
            //     //编辑
            //     if(row != undefined && row.length==1){
            //         // var id=row[0].id;
            //         $("#icon").combobox({
            //             url: iconDataUrl,
            //             valueField: "value",
            //             textField: "name",
            //             method: 'get',
            //             editable: true,
            //             required: true,
            //         });
            //         $("#templateEdit").form("load",row[0]);
            //         // $('#id').val(id);
            //     }
            // }
        }).dialog('open');
    };

        return Device;
    });
